#include <stdarg.h>
#include <my_header.h>

//日志级别
typedef enum LogLevel
{
    Debug,//调试
    Info,//信息
    Warning,//警告
    Error  //错误
}LogLevel;

const char* getLogLevelString(LogLevel level)
{
    switch(level)
    {
        case Debug:
            return "Debug";
        case Info:
            return "Info";
        case Warning:
            return "Warning";
        case Error:
            return "Error";
    }
        return "unknown";
}

//获取当前时间字符串
const char* getDateTimeString()
{
    time_t _time=time(NULL);
    struct tm *_tm=localtime(&_time);
    static char str[128];
    strftime(str,128,"%Y-%m-%d %H:%M:%S",_tm);

    return str;
}

//日志输出
//文件名，哪一行
void dailylog(LogLevel level,const char *file,int line,const char *fmt,...)
{
    va_list list;
    va_start(list,fmt);
    char buf[1024];
    vsnprintf(buf,1024,fmt,list);
    va_end(list);

    char msg[2048];

    FILE * fp=fopen("./logging","a");
    if(fp!=NULL){
    fprintf(fp,"[%s] %s:%d %s %s\n",getLogLevelString(level),file,line,getDateTimeString(),buf);
    fclose(fp);
    }else{
        fprintf(stderr,"Failed to open log file.\n");
    }
}

#define LOG_DEBUG(fmt,...)  dailylog(Debug,__FILE__,__LINE__,fmt,##__VA_ARGS__);
#define LOG_INFO(fmt,...)  dailylog(Info,__FILE__,__LINE__,fmt,##__VA_ARGS__);
#define LOG_WARNING(fmt,...)  dailylog(Warning,__FILE__,__LINE__,fmt,##__VA_ARGS__);
#define LOG_ERROR(fmt,...)  dailylog(Error,__FILE__,__LINE__,fmt,##__VA_ARGS__);

